using ChuTiJingTai.Models;
using System.Text.Json;
using System.Text;

namespace ChuTiJingTai.Services
{
    /// <summary>
    /// 试卷生成服务实现
    /// </summary>
    public class ExamService : IExamService
    {
        private readonly ILocalStorageService _localStorage;
        private readonly ILogService _logService;
        private readonly HttpClient _httpClient;

        public ExamService(ILocalStorageService localStorage, ILogService logService, HttpClient httpClient)
        {
            _localStorage = localStorage;
            _logService = logService;
            _httpClient = httpClient;
        }

        public async Task<ExamPaper> GenerateExamAsync(ExamGenerationRequest request)
        {
            try
            {
                await _logService.LogInfoAsync($"开始生成试卷，类型: {request.ExamType}", "ExamService");
                
                // 获取孩子信息
                var child = await _localStorage.GetChildAsync(request.ChildId);
                if (child == null)
                {
                    throw new ArgumentException("未找到指定的孩子档案");
                }

                // 获取API配置
                var apiConfig = await _localStorage.GetApiConfigAsync();
                if (apiConfig == null || string.IsNullOrEmpty(apiConfig.ApiKey))
                {
                    throw new InvalidOperationException("请先配置AI模型API");
                }

                // 构建试卷标题
                var title = $"{child.Name}_{request.ExamType}_{DateTime.Now:yyyyMMdd_HHmm}";

                // 生成题目（这里先用模拟数据，实际应调用AI API）
                var questions = await GenerateQuestionsAsync(request, child, apiConfig);

                // 创建试卷
                var examPaper = new ExamPaper
                {
                    Title = title,
                    Type = request.ExamType,
                    ChildId = request.ChildId,
                    Questions = questions,
                    Difficulty = request.Difficulty,
                    GenerateMode = "AI生成",
                    CreateTime = DateTime.Now
                };

                // 保存试卷
                await _localStorage.SaveExamPaperAsync(examPaper);
                
                await _logService.LogInfoAsync($"试卷生成完成: {title}", "ExamService");
                return examPaper;
            }
            catch (Exception ex)
            {
                await _logService.LogErrorAsync($"生成试卷失败: {ex.Message}", "ExamService", ex.ToString());
                throw;
            }
        }

        private async Task<List<Question>> GenerateQuestionsAsync(ExamGenerationRequest request, ChildProfile child, ApiConfig apiConfig)
        {
            // 根据试卷类型生成不同的题目
            return request.ExamType switch
            {
                ExamTypes.MathApplication => await GenerateMathQuestionsAsync(request, child),
                ExamTypes.ChinesePinyinToHanzi => await GenerateChinesePinyinQuestionsAsync(request, child),
                ExamTypes.ChineseHanziToPinyin => await GenerateChineseHanziQuestionsAsync(request, child),
                ExamTypes.ChineseEssayReading => await GenerateChineseReadingQuestionsAsync(request, child),
                _ => await GenerateGenericQuestionsAsync(request, child)
            };
        }

        private async Task<List<Question>> GenerateMathQuestionsAsync(ExamGenerationRequest request, ChildProfile child)
        {
            // 模拟数学应用题生成
            var questions = new List<Question>();
            for (int i = 1; i <= request.QuestionCount; i++)
            {
                questions.Add(new Question
                {
                    Id = $"math_{i}",
                    Type = "应用题",
                    Content = $"小明有{i * 2}个苹果，小红有{i * 3}个苹果，他们一共有多少个苹果？",
                    Answer = $"{i * 2 + i * 3}",
                    Score = 10
                });
            }
            
            await Task.Delay(100); // 模拟API调用延迟
            return questions;
        }

        private async Task<List<Question>> GenerateChinesePinyinQuestionsAsync(ExamGenerationRequest request, ChildProfile child)
        {
            // 模拟拼音写汉字题目生成
            var questions = new List<Question>();
            var words = new[] { "学习", "朋友", "快乐", "努力", "成功", "梦想", "希望", "勇敢", "坚持", "创新" };
            
            for (int i = 0; i < Math.Min(request.QuestionCount, words.Length); i++)
            {
                questions.Add(new Question
                {
                    Id = $"pinyin_{i + 1}",
                    Type = "看拼音写汉字",
                    Content = $"请写出拼音 'xué xí' 对应的汉字：",  // 这里应该根据实际单词生成拼音
                    Answer = words[i],
                    Score = 5
                });
            }
            
            await Task.Delay(100);
            return questions;
        }

        private async Task<List<Question>> GenerateChineseHanziQuestionsAsync(ExamGenerationRequest request, ChildProfile child)
        {
            // 模拟汉字写拼音题目生成
            var questions = new List<Question>();
            var words = new[] { "电脑", "图书", "音乐", "画画", "运动", "科学", "历史", "地理", "数学", "语文" };
            
            for (int i = 0; i < Math.Min(request.QuestionCount, words.Length); i++)
            {
                questions.Add(new Question
                {
                    Id = $"hanzi_{i + 1}",
                    Type = "看汉字写拼音",
                    Content = $"请写出汉字 '{words[i]}' 的拼音：",
                    Answer = "diàn nǎo", // 这里应该根据实际单词生成拼音
                    Score = 5
                });
            }
            
            await Task.Delay(100);
            return questions;
        }

        private async Task<List<Question>> GenerateChineseReadingQuestionsAsync(ExamGenerationRequest request, ChildProfile child)
        {
            // 模拟语文阅读题目生成
            var questions = new List<Question>
            {
                new Question
                {
                    Id = "reading_1",
                    Type = "阅读理解",
                    Content = "春天来了，小草绿了，花儿开了。小鸟在树上唱着美妙的歌声，蝴蝶在花丛中翩翩起舞。\n\n问题：文中描述了春天的哪些景象？",
                    Answer = "小草绿了、花儿开了、小鸟唱歌、蝴蝶飞舞",
                    Score = 15
                }
            };
            
            await Task.Delay(100);
            return questions;
        }

        private async Task<List<Question>> GenerateGenericQuestionsAsync(ExamGenerationRequest request, ChildProfile child)
        {
            // 模拟通用题目生成
            var questions = new List<Question>();
            for (int i = 1; i <= request.QuestionCount; i++)
            {
                questions.Add(new Question
                {
                    Id = $"general_{i}",
                    Type = "综合题",
                    Content = $"这是第{i}道综合题目，请根据你的知识回答。",
                    Answer = $"答案{i}",
                    Score = 10
                });
            }
            
            await Task.Delay(100);
            return questions;
        }

        public async Task<ExamResult> CorrectExamAsync(ExamPaper paper, string answers)
        {
            try
            {
                await _logService.LogInfoAsync($"开始批改试卷: {paper.Title}", "ExamService");
                
                // 解析学生答案
                var studentAnswers = ParseAnswers(answers);
                
                // 批改每道题
                var questionResults = new List<QuestionResult>();
                int totalScore = 0;
                int score = 0;
                
                foreach (var question in paper.Questions)
                {
                    var studentAnswer = studentAnswers.GetValueOrDefault(question.Id, "");
                    var isCorrect = CompareAnswers(studentAnswer, question.Answer);
                    var questionScore = isCorrect ? question.Score : 0;
                    
                    questionResults.Add(new QuestionResult
                    {
                        QuestionId = question.Id,
                        StudentAnswer = studentAnswer,
                        CorrectAnswer = question.Answer,
                        IsCorrect = isCorrect,
                        Score = questionScore,
                        Comment = isCorrect ? "正确" : "答案错误"
                    });
                    
                    totalScore += question.Score;
                    score += questionScore;
                }
                
                var result = new ExamResult
                {
                    ExamId = paper.Id,
                    TotalScore = totalScore,
                    Score = score,
                    QuestionResults = questionResults,
                    CorrectTime = DateTime.Now,
                    Analysis = GenerateAnalysis(questionResults)
                };
                
                await _logService.LogInfoAsync($"试卷批改完成，得分: {score}/{totalScore}", "ExamService");
                return result;
            }
            catch (Exception ex)
            {
                await _logService.LogErrorAsync($"批改试卷失败: {ex.Message}", "ExamService", ex.ToString());
                throw;
            }
        }

        private Dictionary<string, string> ParseAnswers(string answers)
        {
            var result = new Dictionary<string, string>();
            
            // 简单的答案解析，实际应该更复杂
            var lines = answers.Split('\n', StringSplitOptions.RemoveEmptyEntries);
            foreach (var line in lines)
            {
                var parts = line.Split(':', 2);
                if (parts.Length == 2)
                {
                    result[parts[0].Trim()] = parts[1].Trim();
                }
            }
            
            return result;
        }

        private bool CompareAnswers(string studentAnswer, string correctAnswer)
        {
            // 简单的答案比较，实际应该更智能
            return string.Equals(studentAnswer.Trim(), correctAnswer.Trim(), StringComparison.OrdinalIgnoreCase);
        }

        private string GenerateAnalysis(List<QuestionResult> questionResults)
        {
            var wrongCount = questionResults.Count(q => !q.IsCorrect);
            var accuracy = (double)(questionResults.Count - wrongCount) / questionResults.Count * 100;
            
            var analysis = new StringBuilder();
            analysis.AppendLine($"答题准确率: {accuracy:F1}%");
            
            if (wrongCount > 0)
            {
                analysis.AppendLine($"错题数量: {wrongCount}道");
                analysis.AppendLine("需要重点复习的知识点：");
                
                foreach (var wrong in questionResults.Where(q => !q.IsCorrect))
                {
                    analysis.AppendLine($"- 题目{wrong.QuestionId}: {wrong.Comment}");
                }
            }
            else
            {
                analysis.AppendLine("恭喜！全部答对了，继续保持！");
            }
            
            return analysis.ToString();
        }

        public async Task<List<ExamPaper>> GetExamsAsync(int? childId = null)
        {
            try
            {
                if (childId.HasValue)
                {
                    return await _localStorage.GetExamPapersByChildAsync(childId.Value);
                }
                return await _localStorage.GetExamPapersAsync();
            }
            catch (Exception ex)
            {
                await _logService.LogErrorAsync($"获取试卷列表失败: {ex.Message}", "ExamService");
                return new List<ExamPaper>();
            }
        }

        public async Task<bool> DeleteExamAsync(int examId)
        {
            try
            {
                var result = await _localStorage.DeleteExamPaperAsync(examId);
                if (result)
                {
                    await _logService.LogInfoAsync($"删除试卷: {examId}", "ExamService");
                }
                return result;
            }
            catch (Exception ex)
            {
                await _logService.LogErrorAsync($"删除试卷失败: {ex.Message}", "ExamService");
                return false;
            }
        }
    }
} 